package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 营业额统计接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //1、获取begin-end每一天的日期
        List<LocalDate> dateList = getLocalDateList(begin, end);
        List<BigDecimal> turnoverList = new ArrayList<>();
        log.info("每次生成的集合：{}", dateList);
        //2、查询当天所所有的已完成单数，并且以下单时间在当天准下单
        HashMap<String, Object> map = new HashMap<>();
        for (LocalDate date : dateList) {
            map.put("begin", LocalDateTime.of(date, LocalTime.MIN));
            map.put("end", LocalDateTime.of(date,LocalTime.MAX));
            map.put("status", Orders.COMPLETED);
            BigDecimal turnOver = reportMapper.queryTurnoverByLocalDateTimeAndStatus(map);
            if (turnOver == null) {
                turnOver = new BigDecimal(0);
            }
            turnoverList.add(turnOver);
        }

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))//注意别导错包了，是commons.lang里的
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    /**
     * 用户统计接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getLocalDateList(begin, end);
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        log.info("每次生成的集合：{}", dateList);
        //2、查询当天所所有的已完成单数，并且以下单时间在当天准下单
        Map<String, Object> map = new HashMap<>();
        for (LocalDate date : dateList) {
            map.put("begin", LocalDateTime.of(date, LocalTime.MIN));
            map.put("end", LocalDateTime.of(date, LocalTime.MAX));
            Integer newUserNumber = reportMapper.queryUserNumber(map);
            newUserList.add(newUserNumber);
            Integer totalUserNumber = reportMapper.queryUserNumber(Collections.singletonMap("end", LocalDateTime.of(date, LocalTime.MAX)));
            totalUserList.add(totalUserNumber);
        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))//注意别导错包了，是commons.lang里的
                .totalUserList(StringUtils.join(totalUserList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .build();
    }

    /**
     * 订单统计接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //1、dateList获取
        List<LocalDate> dateList = getLocalDateList(begin, end);//日期
        List<Integer> orderCountList = new ArrayList<>();//每日订单数
        List<Integer> validOrderCountList = new ArrayList<>();//每日有效订单数
/*        Integer totalOrderCount = 0;//订单总数
        Integer validOrderCount = 0;//有效订单总数*/
        for (LocalDate date : dateList) {
            Map<String, Object> map = new HashMap<>();
            map.put("begin", LocalDateTime.of(date, LocalTime.MIN));
            map.put("end", LocalDateTime.of(date, LocalTime.MAX));
            Integer orderPerDayCountNumber =reportMapper.queryOrderNumber(map);//每日订单总量
            orderCountList.add(orderPerDayCountNumber);
            map.put("status", Orders.COMPLETED);
            Integer validOrderNumber = reportMapper.queryOrderNumber(map);//每日订单数量
            validOrderCountList.add(validOrderNumber);
        }
        Integer totalOrderCount = orderCountList.stream().reduce(0, Integer::sum);//订单总数
        Integer validOrderCount = validOrderCountList.stream().reduce(0, Integer::sum);
        Double orderCompletionRate=0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate= (validOrderCount+0.0)/totalOrderCount;//订单完成率
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, "."))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();

    }

    /**
     * 查询销量排名top10接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
//        List<LocalDate> dateList = getLocalDateList(begin, end);//日期
        List<Map> mapList=reportMapper.queryOrderTop10(LocalDateTime.of(begin,LocalTime.MIN),LocalDateTime.of(end,LocalTime.MAX),Orders.COMPLETED);
        log.info(mapList.toString());
        List<Object> nameList = mapList.stream().map(map -> map.get("name")).collect(Collectors.toList());
        List<Object> numberList =mapList.stream().map(map -> map.get("topNumber")).collect(Collectors.toList());
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    /**
     * 报表统计下载
     * @param response
     */
    @Override
    public void exportExcel(HttpServletResponse response) {
        //1、查询进30天的数据
        LocalDate end = LocalDate.now().minusDays(1);
        LocalDate begin = end.minusDays(30);
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));

        try (
                InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
                XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
                ServletOutputStream outputStream = response.getOutputStream()
        ) {
            //概览数据
            XSSFSheet sheet = workbook.getSheet("sheet1");
            sheet.getRow(1).getCell(1).setCellValue("时间："+begin+"至"+end);
            sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
            sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());

            //获取30天的数据
            LocalDate currentDate = begin;
            int startRow = 7; // 假设数据从第6行开始
            while (!currentDate.isAfter(end)) {
                BusinessDataVO dailyData = workspaceService.getBusinessData(LocalDateTime.of(currentDate, LocalTime.MIN), LocalDateTime.of(currentDate, LocalTime.MAX));
                XSSFRow row = sheet.createRow(startRow);
                row.createCell(1).setCellValue(currentDate.toString());
                row.createCell(2).setCellValue(dailyData.getTurnover());
                row.createCell(3).setCellValue(dailyData.getOrderCompletionRate());
                row.createCell(4).setCellValue(dailyData.getNewUsers());
                row.createCell(5).setCellValue(dailyData.getValidOrderCount());
                row.createCell(6).setCellValue(dailyData.getUnitPrice());
                currentDate = currentDate.plusDays(1);
                startRow++;
            }
            workbook.write(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static List<LocalDate> getLocalDateList(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        LocalDate localDate = begin.minusDays(1);
        while (localDate.isBefore(end)) {
            localDate = localDate.plusDays(1);
            dateList.add(localDate);
        }
        return dateList;
    }
}
